package com.xiaoyu.client.ui.fragment.mall.store;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.xiaoyu.client.ClientConstants;
import com.xiaoyu.client.R;
import com.xiaoyu.client.adapter.mall.GoodsForTagAdapter;
import com.xiaoyu.client.adapter.mall.GoodsTypeAdapter;
import com.xiaoyu.client.loader.banner.BannerImageLoader;
import com.xiaoyu.client.model.goods.GoodsBean;
import com.xiaoyu.client.model.goods.GoodsParam;
import com.xiaoyu.client.model.goods.GoodsTagBean;
import com.xiaoyu.client.model.goods.GoodsTagBean.GoodsTagParam;
import com.xiaoyu.client.model.store.StoreDetailBean;
import com.xiaoyu.client.network.NetworkManager;
import com.xiaoyu.client.ui.activity.PhotoViewActivity;
import com.xiaoyu.client.ui.activity.mall.GoodsDetailsActivity;
import com.xiaoyu.client.ui.activity.mall.GoodsMoreTagActivity;
import com.xiaoyu.client.ui.activity.mall.StoreActivity;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.base.BaseFragment;
import com.xiaoyu.commonlib.ui.widget.AutofitHeightViewPager;
import com.xiaoyu.commonlib.ui.widget.NestedListView;
import com.xiaoyu.commonlib.utils.ToastUtil;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 商家产品fragment
 */
public class StoreProductFragment extends BaseFragment {
    private View mView;
    @BindView(R.id.store_product_banner)
    Banner mBanner;//类型列表
    @BindView(R.id.activity_goods_more_tag_list_container)
    NestedListView mTagContainer;//类型列表
    @BindView(R.id.activity_goods_more_tag_name)
    TextView mTagNameTxt;//类型名称
    @BindView(R.id.item_goods_refresh_layout)
    SmartRefreshLayout mRefreshLayout;//刷新控件
    @BindView(R.id.item_goods_list_container)
    NestedListView mGoodsContainer;//商品列表

    private GoodsTypeAdapter mTagAdapter;//类型列表适配器
    private GoodsForTagAdapter mGoodsAdapter;//商品列表适配器
    private List<GoodsTagParam> mTagList = new ArrayList<>();//类型数据集合
    private List<GoodsParam> mGoodsList = new ArrayList<>();//商品数据集合
    private List<String> mBannerList = new ArrayList<>();//轮播图数据
    private String storeId;//商家id
    private String tagId;//商品类型id
    private int page = 1;//当前页数
    private int totalPage;//总页数

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mView == null) {
            mView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_store_product, container, false);
            ButterKnife.bind(this, mView);
            initView();
            getTagInfo();
        }
        ViewGroup parent = (ViewGroup) mView.getParent();
        if (parent != null) {
            parent.removeView(mView);
        }
        return mView;
    }

    private void initView() {
        Bundle bundle = getArguments();
        int pos = bundle.getInt(AutofitHeightViewPager.POSITION);
        ((StoreActivity) getActivity()).mViewPager.setViewPosition(mView,pos);
        storeId = bundle.getString(ClientConstants.STORE_ID);
        StoreDetailBean.DataBean data = (StoreDetailBean.DataBean) bundle.getSerializable(ClientConstants.MERCHANT_INFO);
        mBannerList.clear();
        mBannerList.addAll(data.getStorebanner());

        //商品类型列表
        mTagAdapter = new GoodsTypeAdapter(getActivity(), mTagList);
        mTagContainer.setAdapter(mTagAdapter);
        mTagContainer.setOnItemClickListener(onTagClickListener);


        //商品列表
        mGoodsAdapter = new GoodsForTagAdapter(getActivity(),mGoodsList);
        mGoodsContainer.setAdapter(mGoodsAdapter);
        mGoodsContainer.setOnItemClickListener(onGoodsClickListener);

        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.setEnableLoadMore(true);
        mRefreshLayout.setOnLoadMoreListener(onLoadMoreListener);
        mRefreshLayout.setNoMoreData(false);


        //顶部轮播图
        mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        mBanner.setIndicatorGravity(BannerConfig.CENTER);
        mBanner.isAutoPlay(true);
        mBanner.setViewPagerIsScroll(true);
        mBanner.setDelayTime(2000);
        mBanner.setImageLoader(new BannerImageLoader());
        mBanner.setImages(mBannerList);
        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Intent intent = new Intent(getActivity(),PhotoViewActivity.class);
                intent.putExtra(ClientConstants.IMAGER_LIST_URL, (Serializable) mBannerList);
                intent.putExtra(ClientConstants.IMAGER_CLICK_POS, position);
                startActivity(intent);
            }
        });

        mBanner.setFocusable(true);
        mBanner.setFocusableInTouchMode(true);
        mBanner.requestFocus();
        mBanner.start();
    }

    /**
     * 类型item点击监听
     */
    private AdapterView.OnItemClickListener onTagClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            tagId = mTagList.get(position).getGoodstagid();
            mTagAdapter.setSelectId(tagId);
            mTagNameTxt.setText(mTagList.get(position).getGoodstagname());
            mGoodsList.clear();
            mGoodsAdapter.updateList(mGoodsList);
            getGoodsInfo();
        }
    };


    /**
     * 商品item点击监听
     */
    private AdapterView.OnItemClickListener onGoodsClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(getActivity(),GoodsDetailsActivity.class);
            intent.putExtra(ClientConstants.GOODS_ID,mGoodsList.get(position).getGoodsid());
            startActivity(intent);
        }
    };

    //商品列表加载更多
    private OnLoadMoreListener onLoadMoreListener = new OnLoadMoreListener() {
        @Override
        public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            if (page < totalPage){
                page = page + 1;
                getGoodsInfo();
                mRefreshLayout.setNoMoreData(false);
                mRefreshLayout.finishLoadMore();
            }else {
                mRefreshLayout.setNoMoreData(true);
                mRefreshLayout.finishLoadMore();
                mRefreshLayout.finishLoadMoreWithNoMoreData();
                ToastUtil.showBelowToast(getActivity(),"已经没有更多数据！！！");
            }
        }
    };

    /**
     * 获取产品分类信息
     */
    private void getTagInfo() {
        NetworkManager.getGoodsTagList(new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                parseTagInfoSuc(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {

            }
        });
    }

    private void parseTagInfoSuc(String result) {
        GoodsTagBean bean = new Gson().fromJson(result, GoodsTagBean.class);
        mTagList.clear();
        mTagList.addAll(bean.getData());
        mTagAdapter.updateList(mTagList);
        mTagNameTxt.setText(mTagList.get(0).getGoodstagname());
        tagId = mTagList.get(0).getGoodstagid();

        mTagAdapter.setSelectId(tagId);

        getGoodsInfo();

    }

    /**
     * 获取商品信息
     */
    private void getGoodsInfo(){
        NetworkManager.getGoodsByStoreList(page, tagId,storeId, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                parseGoodsInfoSuc(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {

            }
        });
    }

    private void parseGoodsInfoSuc(String result) {
        ToastUtil.logResult("商家商品信息",result);
        if (page == 1){
            mGoodsList.clear();
            mGoodsAdapter.updateList(mGoodsList);
        }
        GoodsBean bean = new Gson().fromJson(result,GoodsBean.class);
        totalPage = Integer.parseInt(bean.getData().getCount());
        if (totalPage == 1){
            mRefreshLayout.setEnableLoadMore(false);
        }else {
            mRefreshLayout.setEnableLoadMore(true);
        }
        mGoodsList.addAll(bean.getData().getList());
        mGoodsAdapter.updateList(mGoodsList);
    }

}
